const std = @import("std");
const httpz = @import("httpz");
const userController = @import("../controller/user_controller.zig");
const articleController = @import("../controller/article_controller.zig");
const cateController = @import("../controller/cate_controller.zig");

/// 初始化路由
pub fn initRoute() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();

    var server = try httpz.Server().init(allocator, .{
        .port = 5588,
        // 跨域设置
        .cors = .{
            .origin = "*",
            .methods = "GET, POST, PUT, DELETE, OPTIONS, PATCH",
            .headers = "*",
        },
    });
    defer server.deinit();

    // 错误404和500错误处理
    server.notFound(&notFound);
    server.errorHandler(&errorHandler);

    // 创建路由
    var router = server.router();

    // 注册路由
    // 首页博客列表
    router.get("/api/home/articles", &articleController.getHomeArticles);
    // 首页分类列表
    router.get("/api/home/cates", &cateController.getHomeCategories);
    // 某分类下博客文章
    router.get("/api/cate/articles", &articleController.getArticlesByCateName);
    // 文章详情
    router.get("/api/article/:id", &articleController.getArticleDetail);
    // 文章搜索
    router.get("/api/article/search", &articleController.searchArticles);
    // 归档文章
    router.get("/api/article/archive", &articleController.getArchiveArticles);

    // 管理员登录
    router.post("/admin/user/login", &userController.login);
    // 获取文章列表
    router.get("/admin/articles", &articleController.getArticleListPaginate);
    // 添加文章
    router.post("/admin/articles", &articleController.addArticle);
    // 编辑文章
    router.put("/admin/articles", &articleController.editArticle);
    // 删除文章
    router.delete("/admin/articles/:id", &articleController.deleteArticleById);
    // 批量删除文章
    router.post("/admin/articles/batchDelete", &articleController.deleteArticleBatch);

    // 获取分类列表
    router.get("/admin/categories", &cateController.getCategoryList);
    // 添加分类
    router.post("/admin/categories", &cateController.addCategory);
    // 编辑分类
    router.put("/admin/categories", &cateController.editCategory);
    // 删除分类
    router.delete("/admin/categories/:id", &cateController.deleteCategoryById);
    // 批量删除分类
    router.post("/admin/categories/batchDelete", &cateController.deleteCategoryBatch);

    std.log.info("Server listening on http://localhost:5588", .{});

    try server.listen();
}

/// 处理404错误
fn notFound(_: *httpz.Request, res: *httpz.Response) !void {
    res.status = 404;
    return try res.json(.{ .code = 404, .msg = "Not Found" }, .{});
}

/// 处理500错误
fn errorHandler(_: *httpz.Request, res: *httpz.Response, _: anyerror) void {
    res.status = 500;
    return res.json(.{ .code = 500, .msg = "Internal Server Error" }, .{}) catch return;
}

// fn errorHandler(_: *httpz.Request, res: *httpz.Response, _: anyerror) void {
//     res.status = 500;
//     res.content_type = httpz.ContentType.JSON;
//     res.body = "Internal Server Error";
// }
